package com.xiaojian.pick.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.xiaojian.pick.entity.Comment;
import com.xiaojian.pick.entity.CommodityComment;
import com.xiaojian.pick.mapper.CommentMapper;
import com.xiaojian.pick.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 小贱
 * @date 2020/11/23 - 1:47
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public Page<Comment> findByPage(Integer cId, Integer page, Integer limit) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("topic_id", cId)
                .eq("reply_id", 0)
                .orderByDesc("time");
        //Page<Comment> commentPage = this.page(new Page<>(page, limit), queryWrapper);
        List<Comment> records = list(queryWrapper);
        if(records != null){
            records.forEach(record -> {
                record.setCommId(record.getId());
                record.setChildren(children(cId, record.getId()));
                record.setShow(false);
            });
        }
        Page<Comment> commentPage = new Page<>();
        commentPage.setRecords(records);
        return commentPage;
    }

    private List<Comment> children(Integer cid, Integer replyId){
        List<Comment> list = this.list(new QueryWrapper<Comment>()
                .eq("topic_id", cid)
                .eq("reply_id", replyId)
                .orderByDesc("time"));
        if(list != null){
            List<Comment> res = new ArrayList<>();
            for (int i = 0; i < list.size(); i++){
                Comment comment = list.get(i);
                if(i == 0){
                    comment.setShow(true);
                }
                comment.setCommId(comment.getReplyId());
                res.add(comment);
            }
            list = res;
        }
        return list;
    }


    @Override
    public List<Comment> findByTopicId(Integer topicId) {
        return commentMapper.findByTopicId(topicId);
    }

    @Override
    public int addComment(Comment comment) {
        return commentMapper.addComment(comment);
    }

    @Override
    public int updateCommentState(Comment comment) {
        return commentMapper.updateCommentState(comment);
    }

}
